<template>
    <div class="line-edit">
        <div class="line-header">
            <h2>{{ state.editType == 'edit' ? '编辑线路' : '新增线路' }}</h2>
        </div>
        <div class="line-content" style="flex: 1; overflow-y: auto;overflow-x: hidden;">
            <a-row :gutter="48" style="height: 100%;overflow: hidden;">
                <a-col :span="10" style="height: 100%;overflow: auto;">
                    <!-- 基础信息表单 -->
                    <div class="form-section">
                        <a-row :gutter="24">
                            <a-col :span="24">
                                <a-form-item label="线路名称" required :label-col="{ style: 'width:120px' }">
                                    <a-input v-model:value="formState.name" placeholder="请输入名称"
                                        style="width: 100%" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="线路状态" required :label-col="{ style: 'width:120px' }">
                                    <a-radio-group v-model:value="formState.optStatus" :options="getEnumOptions('optStatus')" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </div>

                    <!-- 绘制线路 -->
                    <div class="draw-section">
                        <h3>绘制线路</h3>

                        <!-- 坐标点列表 -->
                        <div class="coordinate-list">
                            <a-table :columns="coordinateColumns" :data-source="formState.areaList" :pagination="false"
                                size="small">
                                <template #bodyCell="{ column, record, index }">
                                    <template v-if="column.dataIndex === 'fencePoint'">
                                        {{ index + 1 }}
                                    </template>
                                    <template v-if="column.dataIndex === 'lo'">
                                        {{ record.lo }}
                                    </template>
                                    <template v-if="column.dataIndex === 'la'">
                                        {{ record.la }}
                                    </template>
                                    <template v-if="column.dataIndex === 'operation'">
                                        <a @click="deleteCoordinate(index)" style="color: #ff4d4f;">删除</a>
                                    </template>
                                </template>
                            </a-table>
                        </div>
                    </div>
                    
                    <a-form-item label="备注:">
                        <a-textarea v-model:value="formState.description" placeholder="请输入备注信息" :maxlength="50" :rows="3"
                            show-count />
                    </a-form-item>
                </a-col>
                <a-col :span="14" style="height: 100%;">
                    <!-- 地图区域 -->
                    <div class="map-container">
                        <div class="map-header">
                            <a-input placeholder="搜索/选择地址" id='search_station' style="width: 200px;" v-model:value="searchAddress"/>
                            <div class="map-controls">
                                <a-button :type="state.isDrawing ? 'primary' : 'default'" @click="toggleDrawing"
                                    size="small">
                                    <EditOutlined />
                                </a-button>
                                <a-button :type="state.isSatellite ? 'primary' : 'default'" @click="toggleSatellite"
                                    size="small">
                                    <GlobalOutlined />
                                </a-button>
                            </div>
                        </div>
                        <div id="line-map" class="map-content"></div>
                    </div>
                </a-col>
            </a-row>
        </div>
        <!-- 操作按钮 -->
        <div class="bottom-section">
            <div class="action-buttons">
                <a-button @click="handleCancel">取消</a-button>
                <a-button type="primary" class="ant-btn" @click="handleConfirm">确认</a-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import { EditOutlined, GlobalOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { bizLineAdd,bizLineDetail, bizLineUpdate } from '@/service/nmcApi'
import { getEnumOptions } from '@/utils/enum'

const emit = defineEmits(['update:visible', 'success'])

const state = reactive({
    editType: 'add',
    isDrawing: false,
    isSatellite: false
})

const formState = reactive({
    id:null,
    name: '',
    optStatus: 'N',
    areaList: [],
    description: ''
})

const searchAddress = ref('')

// 坐标点表格列配置
const coordinateColumns = [
    {
        title: '围栏点',
        dataIndex: 'fencePoint',
        width: 80
    },
    {
        title: '经度',
        dataIndex: 'lo',
        width: 120
    },
    {
        title: '纬度',
        dataIndex: 'la',
        width: 120
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: 80
    }
]

// 地图相关变量
let mapInstance = null
let polygon = null
let mouseTool = null
let satellite = null
let polyEditor = null
let gaoAutoComplete = null

onMounted(() => {
    initMap()
})

onUnmounted(() => {
    if (mapInstance) {
        mapInstance.destroy()
    }
})

// 初始化地图
const initMap = () => {
    mapInstance = new AMap.Map('line-map', {
        mapStyle: 'amap://styles/whitesmoke',
        doubleClickZoom: false,
        zoom: 13,
        center: [114.325512, 30.367111],
        animateEnable: false
    })

    // 初始化卫星图层
    satellite = new AMap.TileLayer.Satellite()
    mapInstance.addLayer(satellite)
    satellite.hide()
    
    mapInstance.plugin(['AMap.AutoComplete'], () => {
        gaoAutoComplete = new AMap.AutoComplete({
            input: 'search_station',
        })
        gaoAutoComplete.on('select', handleSelectResult)
    })
    
    // 初始化多边形编辑器
    polyEditor = new AMap.PolygonEditor(mapInstance)
    polyEditor.on('addnode', updateCoordinateData)
    polyEditor.on('removenode', updateCoordinateData)
    polyEditor.on('adjust', updateCoordinateData)

    // 初始化鼠标工具
    mouseTool = new AMap.MouseTool(mapInstance)
    mapInstance.add(mouseTool)

    // 绘制完成事件
    mouseTool.on('draw', (event) => {
        mouseTool.close(true)
        state.isDrawing = false

        const path = event.obj._opts.path
        if (path.length > 2) {
            // 清除之前的坐标点，只保留新绘制的区域
            formState.areaList = path.map((point, index) => ({
                lo: point[0],
                la: point[1]
            }))
            drawPolygon()
        }
    })

    // 地图点击事件
    mapInstance.on('click', (e) => {
        if (state.isDrawing) {
            // 绘制模式下的点击处理
        }
    })
}

//高德搜索
const handleSelectResult = (e) => {
    if (e.poi.location) {
        const { lng, lat } = e.poi.location;
        // 地图重新定位
        mapInstance.setCenter(e.poi.location);
        mapInstance.setZoom(16);
    }
}

// 加载编辑数据
const loadEditData = (data, type) => {
    //'edit':'add'
    state.editType = type
    // formState.name = data.name || ''
    // formState.description = data.description || ''

    // // 加载坐标数据
    // if (data.areaList && data.areaList.length > 0) {
    //     formState.areaList = data.areaList
    //     drawPolygon()
    // }

    if(type == 'edit'){
        formState.id = data.id
        bizLineDetail({id:data.id}).then(res => {
            if (res && res.status === "000_0000_0000") {
                formState.name = res.result.name;
                formState.description = res.result.description;
                formState.optStatus = res.result.optStatus;
                formState.areaList = res.result.bizLineArea.pointList;
                drawPolygon()
            }
        })
    }else{
        formState.id = null
        formState.areaList = [];
        formState.name = '';
        formState.description = '';
        formState.optStatus = 'N';
    }
}

// 绘制多边形
const drawPolygon = () => {
    // 清除现有多边形
    if (polygon) {
        mapInstance.remove(polygon)
    }
    
    if (formState.areaList.length >= 3) {
        const path = formState.areaList.map(point => [point.lo, point.la])
        
        polygon = new AMap.Polygon({
            path: path,
            fillColor: '#52c41a', // 绿色，符合原型图
            fillOpacity: 0.2,
            strokeWeight: 2,
            strokeColor: '#52c41a'
        })
        
        mapInstance.add(polygon)
        mapInstance.setFitView([polygon], false, [60, 60, 60, 60], 16)
        
        // 绑定点击事件
        polygon.on('click', () => {
            if (polyEditor) {
                polyEditor.setTarget(polygon)
                polyEditor.open()
            }
        })
    }
}

// 更新坐标数据
const updateCoordinateData = (e) => {
    const path = e.target._opts.path
    if (path.length > 0) {
        // 更新坐标列表
        formState.areaList = path.map((point, index) => ({
            lo: point[0],
            la: point[1]
        }))
    }
}

// 删除坐标点
const deleteCoordinate = (index) => {
    formState.areaList.splice(index, 1)
    if (formState.areaList.length >= 3) {
        drawPolygon()
    } else {
        // 如果坐标点少于3个，清除多边形
        if (polygon) {
            mapInstance.remove(polygon)
            polygon = null
        }
    }
}

// 切换绘制模式
const toggleDrawing = () => {
    state.isDrawing = !state.isDrawing
    if (state.isDrawing) {
        polyEditor.close()
        // 清除之前的坐标点，开始新的绘制
        formState.areaList = []
        if (polygon) {
            mapInstance.remove(polygon)
            polygon = null
        }
        mouseTool.polygon({
            fillColor: '#52c41a',
            fillOpacity: 0.2,
            strokeWeight: 2,
            strokeColor: '#52c41a'
        })
    } else {
        mouseTool.close(true)
    }
}

// 切换卫星图层
const toggleSatellite = () => {
    state.isSatellite = !state.isSatellite
    if (state.isSatellite) {
        satellite.show()
    } else {
        satellite.hide()
    }
}

// 取消
const handleCancel = () => {
    emit('update:visible', false)
}

// 确认
const handleConfirm = () => {
    if (!formState.name) {
        message.error('请输入线路名称')
        return
    }

    if (formState.areaList.length < 3) {
        message.error('请至少绘制3个坐标点')
        return
    }

    const submitData = {
        ...formState,
        name: formState.name
    }
    //计算围栏周长
    const perimeter = calculatePerimeter(formState.areaList)
    submitData.distance = perimeter

    // 这里可以调用API保存数据
    console.log('提交数据:', submitData)
    let axiosFn = state.editType == 'edit' ? bizLineUpdate : bizLineAdd
    axiosFn(submitData).then(res => {
        if (res && res.status === "000_0000_0000") {
            message.success(state.editType == 'edit'  ? '编辑成功' : '新增成功')
            emit('success', submitData)
            emit('update:visible', false)
        } else {
            message.error('操作失败')
        }
    }).catch(err => {
        console.error('操作失败:', err)
        message.error('操作失败')
    })

}

//计算围栏周长 
// 根据经纬度计算周长，单位为米
const calculatePerimeter = (areaList) => {
    // 地球半径，单位为米
    const R = 6371000
    let perimeter = 0
    for (let i = 0; i < areaList.length; i++) {
        const currentPoint = areaList[i]
        const nextPoint = areaList[(i + 1) % areaList.length]
        // 将经纬度从度转为弧度
        const lat1 = currentPoint.la * Math.PI / 180
        const lon1 = currentPoint.lo * Math.PI / 180
        const lat2 = nextPoint.la * Math.PI / 180
        const lon2 = nextPoint.lo * Math.PI / 180

        // 使用Haversine公式计算两点间距离
        const dLat = lat2 - lat1
        const dLon = lon2 - lon1
        const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                  Math.cos(lat1) * Math.cos(lat2) *
                  Math.sin(dLon / 2) * Math.sin(dLon / 2)
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
        const distance = R * c
        perimeter += distance
    }
    return Math.round(perimeter)
}

// 暴露方法给父组件
defineExpose({
    loadEditData
})
</script>

<style scoped lang="less">
.line-edit {
    height: 100%;
    background: #fff;
    overflow: hidden;
    position: relative;
    display: flex;
    flex-direction: column;

    .line-header {
        margin-bottom: 24px;

        h2 {
            margin: 0;
            font-size: 18px;
            font-weight: 500;
        }
    }

    .form-section {
        margin-bottom: 24px;
        padding: 16px;
        background: #fafafa;
        border-radius: 6px;
    }

    .draw-section {
        flex: 1;
        margin-bottom: 24px;

        h3 {
            margin-bottom: 16px;
            font-size: 16px;
            font-weight: 500;
        }

        .coordinate-list {
            height: 100%;
        }
    }

    .map-container {
        height: 100%;
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        overflow: hidden;

        .map-header {
            padding: 12px;
            background: #fafafa;
            border-bottom: 1px solid #d9d9d9;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .map-controls {
                display: flex;
                gap: 8px;
            }
        }

        .map-content {
            height: calc(100% - 60px);
            min-height: 400px;
        }
    }

    .bottom-section {
        padding-top: 16px;
        border-top: 1px solid #f0f0f0;

        .action-buttons {
            text-align: right;
            margin-top: 16px;

            .ant-btn {
                margin-left: 8px;
            }
        }
    }
}
</style>